package com.example.jetpacklearn

import android.os.Looper
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent

/**
 *
 * @ClassName:      DataListenerContainer$
 * @Description:    监听数据变化的容器
 * @Author:         xinya
 * @CreateDate:     2020/11/1$ 14:02$
 * @UpdateRemark:   更新内容
 * @Version:        1.0
 */
class DataListenerContainer<T> {
    private val blockList = arrayListOf<(T?) -> Unit>()
    private val viewLifecycleProviderMap = hashMapOf<(T?) -> Unit, Lifecycle>()
    companion object {
        private const val TAG = "DataListenerContainer"
    }
    var value: T? = null
        set(value: T?) {
            field = value
            // 判断当前线程是不是主线程,不是的话切到主线程
            if (Looper.getMainLooper().thread === Thread.currentThread()) {
                blockList.forEach {
                    dispatchValue(it, value)
                }
            } else {
                App.mainHandler.post {
                    blockList.forEach {
                        dispatchValue(it, value)
                    }
                }
            }
        }

    // 判断生命周期 分发
    private fun dispatchValue(it: (T?) -> Unit, value: T?) {
        val lifecycle = viewLifecycleProviderMap[it]
        if (lifecycle != null && lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) {
            it.invoke(value)
            Log.d(TAG, "dispatchValue: ok")
        } else {
            Log.d(TAG, "dispatchValue: else")
        }
    }

    fun addListener(owner: LifecycleOwner, valueObserver: (T?) -> Unit) {
        val lifecycle = owner.lifecycle
        viewLifecycleProviderMap[valueObserver] = lifecycle

        lifecycle.addObserver(MyLifeObserver(valueObserver))

        if (!blockList.contains(valueObserver)) {
            blockList.add(valueObserver)
        }
    }

    private inner class MyLifeObserver (private val valueObserver: (T?) -> Unit) :
        LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun removeValue() {
            Log.d(TAG, "removeValue: ")
            viewLifecycleProviderMap.remove(valueObserver)
        }
    }



}